package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import action.UserAction;

public class UserServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public UserServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
		String name = request.getParameter("userNme");
		String password = request.getParameter("passWord");
		UserAction ua = new UserAction(name,password);
		int result=ua.result();
		Map map = new HashMap();
		map.put("result", "'&nbsp'");
		switch(result){
		case 0: map.put("result", "用户名不存在");break;
		case 1: map.put("result", "登陆成功");break;
		case 2: map.put("result", "密码错误！");break;
		case 4: map.put("result", "密码和用户名都不能为空!");break;
		}
		request.setAttribute("result", map.get("result"));
		if(result==1){
			request.getSession().setAttribute("user", name);
			request.getRequestDispatcher("/jsp/index.jsp").forward(request, response);
		}else{
			request.getRequestDispatcher("/Login.jsp").forward(request, response);
		}
		
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
